package com.practice.线程的interrupt中断方法;

/**
 * @program: tenghw-practice-demo
 * @author: tenghw
 * @create: 2024-08-10 13:24
 * @Version 1.0
 * @description:
 **/
public class Demo1 implements Runnable {
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            // 执行任务...
            System.out.println("线程非中断状态...");
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // 捕获到中断异常
            System.out.println("Thread interrupted！");
            System.out.println(">>>1" + Thread.currentThread().isInterrupted());// false
            Thread.currentThread().interrupt();
            System.out.println(">>>2" + Thread.currentThread().isInterrupted());// true；重新设置中断标志为true
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Demo1());
        thread.start();
        Thread.sleep(100); // 等待一段时间后中断线程
        thread.interrupt(); // 中断线程
    }
}